<template>
  <div class="padding30px">
    <a-card>
      <!-- 搜索区域 -->
      <a-form :model="searchForm" layout="inline" @submit.prevent="handleSearch">
        <a-form-item label="用户名">
          <a-input v-model:value="searchForm.urName" placeholder="输入用户名" />
        </a-form-item>

        <a-form-item label="登录名">
          <a-input v-model:value="searchForm.urUsername" placeholder="输入登录名" />
        </a-form-item>

        <a-form-item label="邮箱">
          <a-input v-model:value="searchForm.urEmail" placeholder="输入邮箱" />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" htmlType="submit">搜索</a-button>
        </a-form-item>

        <a-form-item>
          <a-button @click="resetSearch">重置</a-button>
        </a-form-item>

        <!-- <a-form-item>
          <a-button @click="exporT">导出</a-button>
        </a-form-item> -->
      </a-form>
    </a-card>
    <a-card title="用户管理">
      <a-button type="primary" @click="openAddModal" style="margin-bottom: 16px">新增用户</a-button>
      <a-button @click="deleteSelect" style="margin-left: 16px"
        :disabled="rowSelectionSelecRow.length == 0">删除</a-button>
      <a-table :row-selection="rowSelection" :dataSource="users" :columns="columns" :pagination="pagination"
        @change="handleTableChange" rowKey="urId" bordered>
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.dataIndex === 'index'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'urAvatar'">
            <a-avatar :src="record.urAvatar" />
          </template>

          <template v-else-if="column.dataIndex === 'urSex'">
            {{ record.urSex === 0 ? '男' : '女' }}
          </template>

          <template v-else-if="column.dataIndex === 'urStuats'">
            <a-tag :color="record.urStuats === 1 ? 'green' : 'red'">
              {{ record.urStuats === 1 ? '启用' : '禁用' }}
            </a-tag>
          </template>

          <template v-else-if="column.dataIndex === 'role'">
            {{ record.role.reName }}
          </template>

          <template v-else-if="column.dataIndex === 'createTime'">
            {{ record.createTime }}
          </template>

          <template v-if="column.dataIndex == 'passwT'">
            <a-button @click="uopdateResetSeting(record)">重置密码</a-button>
          </template>

          <template v-else-if="column.dataIndex === 'edit'">
            <a-button @click="openEditModal(record)">编辑</a-button>
          </template>

        </template>
      </a-table>
    </a-card>
    <!-- 新增/编辑用户模态框 -->
    <a-modal :open="modalVisible" :title="isEditMode ? '编辑用户' : '新增用户'" @ok="handleSubmit" @cancel="handleCancel">
      <a-form ref="formRef" :model="currentFormData" :rules="formRules" layout="vertical">
        <a-form-item label="用户名" name="urName">
          <a-input v-model:value="currentFormData.urName" />
        </a-form-item>
        <a-form-item label="头像">
          <image-upload v-model="currentFormData.urAvatar" />
        </a-form-item>
        <a-form-item label="登录名" name="urUsername">
          <a-input v-model:value="currentFormData.urUsername" />
        </a-form-item>

        <a-form-item label="角色" name="urReId">
          <a-select v-model:value="currentFormData.urReId">
            <a-select-option v-for="item in roleList" :key="item" :value="item.reId">{{ item.reName }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item v-if="!isEditMode" label="密码" name="urPassword">
          <a-input-password v-model:value="currentFormData.urPassword" />
        </a-form-item>

        <a-form-item label="邮箱" name="urEmail">
          <a-input v-model:value="currentFormData.urEmail" />
        </a-form-item>

        <a-form-item label="性别">
          <a-radio-group v-model:value="currentFormData.urSex">
            <a-radio :value="0">男</a-radio>
            <a-radio :value="1">女</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="状态">
          <a-switch v-model:checked="currentFormData.urStuats" :checked-value="1" :un-checked-value="0"
            @change="onStatusChange" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { baseRequestClient, requestClient } from '#/api/request';
import ImageUpload from '#/components/ImageUpload.vue'
// API 导入
import {
  getUserListApi,
  updateUserApi,
  addUserApi,
  deleteUserApi,
  resetYourPasswordApi
} from '#/api/object/user'

import {
  findAllRoleApi
} from '#/api/object/role'
const roleList = ref([])

// 通用 CRUD 钩子
import { crud } from '#/components/crud'

// 定义 user 的 crud 接口
const userCrudApi = {
  getList: getUserListApi,
  create: addUserApi,
  update: updateUserApi,
  delete: deleteUserApi,
}

// 初始搜索表单
const initSearchForm = {
  urName: '',
  urUsername: '',
  urEmail: '',
}

//导出表格数据
const exporT = async () => {
  try {
    const url = '/user/export'; // 替换为你的实际路径
    const response = await requestClient.post(url, [], {
      responseType: 'blob', // 必须设置响应类型为 blob
    });

    // 创建下载链接
    const blob = new Blob([response.data]);
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.setAttribute('download', '用户信息.xlsx'); // 设置下载文件名
    document.body.appendChild(link);
    link.click();
    link.remove();

    message.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    message.error('导出失败');
  }
}

const pagination={
   current: 1,
    pageSize: 10,
    total: 0,
}

// 使用 useCrud 管理数据和操作
const {
  dataSource: users,
  searchForm,
  selectedRowKeys: rowSelectionSelecRow,
  modalVisible,
  isEditMode,
  formData: currentFormData,
  loadData,
  handleTableChange,
  handleSearch,
  resetSearch,
  deleteSelected: deleteSelect,
  openAddModal,
  openEditModal,
  handleSubmit,
  handleCancel,
} = crud(userCrudApi, initSearchForm)

// 页面挂载时加载数据
onMounted(() => {
  loadData()
  findAllRoleApi().then(res => {
    //  console.log("res",res.data)
    roleList.value = res.data
  })
})

// 表单验证规则
const formRules = {
  urName: [{ required: true, message: '请输入用户名' }],
  urUsername: [{ required: true, message: '请输入登录名' }],
  // urPassword: [
  //   { required: !isEditMode.value, message: '请输入密码' },
  //   { min: 6, message: '密码长度至少6位' }
  // ],
  urEmail: [{ required: true, message: '请输入邮箱地址' }]
}

// 表格列配置
const columns = [
  { title: '序号', dataIndex: 'index', key: 'index', align: "center" },
  { title: '头像', dataIndex: 'urAvatar', key: 'urAvatar', align: "center" },
  { title: '用户名', dataIndex: 'urName', key: 'urName', align: "center" },
  { title: '登录名', dataIndex: 'urUsername', key: 'urUsername', align: "center" },
  { title: '邮箱', dataIndex: 'urEmail', key: 'urEmail', align: "center" },
  { title: '性别', dataIndex: 'urSex', key: 'urSex', align: "center" },
  { title: '状态', dataIndex: 'urStuats', key: 'urStuats', align: "center" },
  { title: '角色', dataIndex: 'role', key: 'role', align: "center" },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', align: "center" },
  { title: '重置', dataIndex: 'passwT', key: 'passwT', align: "center" },
  { title: '操作', dataIndex: 'edit', key: 'edit', align: "center" },
]

// 行选择配置
const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    rowSelectionSelecRow.value = selectedRows.map(item => item.urId)
  },
  getCheckboxProps: (record) => ({
    disabled: record.name === 'Disabled User',
    name: record.name,
  }),
}

const uopdateResetSeting = (item) => {
  resetYourPasswordApi(item.urId).then(res => {
    loadData()
    message.success('密码重置成功');
  })
}
</script>
